﻿using NaireSystem.Api;
using NaireSystem.Api.Dto;
using NaireSystem.Api.VO;
using NaireSystem.Datas;
using NaireSystem.Enums;
using NaireSystem.ViewModels;
using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using TYBase;
using TYControls;

namespace NaireSystem.Views
{
    /// <summary>
    /// CtrlNaireCreate.xaml 的交互逻辑
    /// </summary>
    public partial class CtrlNaireRecord : TYUserControl
    {
        ViewModelNaireRecord vm = new ViewModelNaireRecord();
        private List<Public_officeVO> listOfficeData;
        private List<QtVO> listQt;
        private string currentExamUuid;
        private List<ExamUserVO> currentUserQts;

        public CtrlNaireRecord()
        {
            InitializeComponent();
            this.DataContext = vm;
            this.Loaded += CtrlNaireCreate_Loaded;
        }

        private async void CtrlNaireCreate_Loaded(object sender, RoutedEventArgs e)
        {
            //搜索未完成的
            if (await InitOffice() == false)
            {
                return;
            }
            pager_record_CurrentPageChanged(null, null);
        }

        #region 题库的

        #endregion

        private async void pager_record_CurrentPageChanged(object sender, Panuon.WPF.SelectedValueChangedRoutedEventArgs<int> e)
        {
            int pageIndex = pager_record.CurrentPage;
            TestQueryDto queryDto = new TestQueryDto()
            {
                examType = (int)EnumExamType.Naire,
            };
            vm.ListNaireRecord.Clear();
            var rData = await Run(() =>
            {
                return ExamApi.ListPublishExam(new PageInfo(pageIndex, 10), queryDto);
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return;
            }
            pager_record.MaxPage = rData.page.PageCount();
            rData.data.ForEach(x =>
            {
                NaireRecordModel quetionModel = UIDataHelper.DataAsUI(x);
                quetionModel.Index = (pageIndex - 1) * rData.page.PageSize + vm.ListNaireRecord.Count + 1;
                vm.ListNaireRecord.Add(quetionModel);
            });
        }

        async Task<bool> InitOffice()
        {
            var rData = await Run(() =>
            {
                return OfficeApi.GetListDeptInfo();
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return false;
            }
            listOfficeData = rData.data;
            return true;
        }
        private async void BtnClick_SelectTest(object sender, RoutedEventArgs e)
        {
            var dx = (sender as Button).DataContext as NaireRecordModel;
            //if (!this.ShowYesNo($"是否进入问卷编辑:{dx.Title}"))
            //    return;
            //开始查询
            var rData = await Run(() =>
            {
                return ExamApi.GetExamWithDepts(dx.data.examUuid);
            });
            currentExamUuid = null;
            vm.EditTest.examUuid = null;
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return;
            }
            currentExamUuid = dx.data.examUuid;
            vm.EditTest.examUuid = rData.data.exam.examUuid;
            vm.EditTest.Title = dx.data.title;
            vm.EditTest.ListQt.Clear();
            vm.ListOffice.Clear();
            vm.ListUser.Clear();
            listQt = rData.data.listQt;
            if (listOfficeData != null)
                foreach (var item in listOfficeData)
                {
                    if (rData.data.listDept != null)
                    {
                        if (rData.data.listDept.Count(x => x.deptUuid == item.s_dept_code) > 0)
                        {
                            vm.ListOffice.Add(new DeptModel
                            {
                                Name = item.s_office,
                                Id = item.s_mark,
                                UserCount = item.userCount,
                                //ExamDeptId=item
                            });
                        }
                    }
                }


            if (rData.data.listQt != null)
            {
                rData.data.listQt.ForEach(x =>
                {
                    QtModel quetionModel = UIDataHelper.DataAsUI(x);
                    foreach (var item in quetionModel.ListOption)
                    {
                        item.IsSelected = false;
                    }
                    quetionModel.Index = vm.EditTest.ListQt.Count + 1;
                    vm.EditTest.ListQt.Add(quetionModel);
                });
            }
        }

        private void BtnClick_AddToTest(object sender, RoutedEventArgs e)
        {
            var dx = (sender as Button).DataContext as QtModel;
            QtModel qt = UIDataHelper.DataAsUI(dx.data);
            qt.Index = vm.EditTest.ListQt.Count + 1;
            vm.EditTest.ListQt.Add(qt);
        }

        private void BtnClick_DeleteFromTest(object sender, RoutedEventArgs e)
        {
            var dx = (sender as Button).DataContext as QtModel;
            //QtModel qt = UIDataHelper.DataAsUI(dx.data);
            vm.EditTest.ListQt.Remove(dx);
            for (int i = 0; i < vm.EditTest.ListQt.Count; i++)
            {
                vm.EditTest.ListQt[i].Index = i + 1;
            }
        }

        bool AsExamData(out CreateTestDto exam)
        {
            exam = new CreateTestDto();
            if (vm.EditTest.Title.Null())
            {
                this.ShowMsg("请输入标题");
                return false;
            }
            Dictionary<string, List<string>> listDeptUser = null;
            List<Tbl_ExamDept> listTestDept = new List<Tbl_ExamDept>();

            foreach (var item in vm.ListOffice)
            {
                if (item.IsSelected)
                    listTestDept.Add(new Tbl_ExamDept { deptUuid = item.Id });
            }

            List<IdAndScoreVo> listId = new List<IdAndScoreVo>();
            foreach (var item in vm.EditTest.ListQt)
            {
                listId.Add(new IdAndScoreVo { id = item.data.qtId, score = item.Score });
            }

            exam = new CreateTestDto()
            {
                exam = new Tbl_Exam
                {
                    createCode = AppData.user.s_ic_no,
                    createTime = DateTime.Now,
                    status = 0,
                    examType = (int)EnumExamType.Naire,
                    title = vm.EditTest.Title,
                    examUuid = vm.EditTest.examUuid,
                },
                listIdAndScore = listId,
                listDeptUser = listDeptUser,
                listDept = listTestDept,
            };
            return true;
        }

        private async void BtnClick_SaveExam(object sender, RoutedEventArgs e)
        {
            if (!AsExamData(out var examData))
            {
                return;
            }
            examData.exam.status = (int)EnumExamStatus.NotPublish;
            var rData = await Run(() =>
            {
                return ExamApi.CreateTest(examData);
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                pager_record_CurrentPageChanged(null, null);
                return;
            }
            vm.EditTest.examUuid = rData.data.examUuid;
            this.ShowMsg("发布成功!");
            pager_record_CurrentPageChanged(null, null);
        }

        private async void BtnClick_PublishExam(object sender, RoutedEventArgs e)
        {
            if (!AsExamData(out var examData))
            {
                return;
            }
            examData.exam.status = (int)EnumExamStatus.Publish;
            var rData = await Run(() =>
            {
                return ExamApi.CreateTest(examData);
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                pager_record_CurrentPageChanged(null, null);
                return;
            }
            currentExamUuid = rData.data.examUuid;
            vm.EditTest.examUuid = rData.data.examUuid;
            this.ShowMsg("发布成功!");
            pager_record_CurrentPageChanged(null, null);
        }

        private void BtnClick_CreateExam(object sender, RoutedEventArgs e)
        {
            vm.EditTest.ListQt.Clear();
            vm.EditTest.examUuid = "";
            vm.EditTest.Title = "";
            foreach (var item in vm.ListOffice)
            {
                item.IsSelected = false;
            }
        }

        private async void BtnClick_SearchUserUnderDept(object sender, RoutedEventArgs e)
        {
            //ExamUserApi
            var dx = (sender as RadioButton).DataContext as DeptModel;

            UserTestQueryDto queryDto = new UserTestQueryDto
            {
                deptId = dx.Id,
                examUuid = currentExamUuid,

            };
            var rData = await Run(() =>
            {
                return ExamUserApi.GetList(queryDto);
            });
            if (rData.code != 0)
            {
                this.ShowMsg(rData.msg);
                return;
            }
            vm.ListUser.Clear();
            currentUserQts = rData.data;
            //这里 需要看哪些人
            foreach (var item in rData.data)
            {
                vm.ListUser.Add(new StringStringData { Key = item.userId, Value = item.userName });
            }
        }

        private void BtnClick_ChooseUser(object sender, RoutedEventArgs e)
        {
            var dx = (sender as RadioButton).DataContext as StringStringData;
            var data = currentUserQts?.FirstOrDefault(x => x.userId == dx.Key);
            if (data == null)
            {
                this.ShowMsg("无用户数据!");
                return;
            }
            vm.EditTest.ExcellentUserId = data.excellentUserId;
            vm.EditTest.ExcellentUserName = data.excellentUserName;

            foreach (var item in data.listAnswer)
            {
                var model = vm.EditTest.ListQt.FirstOrDefault(x => x.data.qtId == item.id);
                if (model != null)
                {
                    for (int j = 0; j < model.ListOption.Count; j++)
                    {
                        model.ListOption[j].IsSelected = item.listAnswer.Contains(j);
                    }
                }
            }
        }

        private Bitmap QrCode(string data)
        {
            QRCodeGenerator.ECCLevel eccLevel = (QRCodeGenerator.ECCLevel.Q);
            using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
            {
                using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(data, eccLevel))
                {
                    using (QRCode qrCode = new QRCode(qrCodeData))
                    {
                        return qrCode.GetGraphic(20);
                    }
                }
            }
        }

        private void BtnClickGetQrCode(object sender, RoutedEventArgs e)
        {
            var dx = (sender as Button).DataContext as NaireRecordModel;
            string examUuid = dx.data.examUuid;
            int examType = dx.data.examType;
            //http://www.lncft.net/wchatkpi/?examUuid={examUuid}&examType={examType}
            string qrData = $"http://www.lncft.net/wchatkpi/?examUuid={examUuid}&examType={examType}";
            var bitmap = QrCode(qrData);

            ViewQRCode view = new ViewQRCode(bitmap);
            view.ShowDialog();
            //string fileName = "";
            //{
            //    var rData = await Run(() =>
            //    {
            //        return ExamApi.GetExamQrCode(examUuid, examType);
            //    });
            //    if (rData.code != 0)
            //    {
            //        this.ShowMsg(rData.msg);
            //        return;
            //    }
            //    fileName = rData.data;
            //}
            //{
            //    var rData = await Run(() =>
            //    {
            //        string saveFileName = (Guid.NewGuid().ToString("N") + ".png").AsFullName();
            //        return FileApi.Download(saveFileName, "tmp_qrcode", fileName);
            //    });
            //    if (rData.code != 0)
            //    {
            //        this.ShowMsg(rData.msg);
            //        return;
            //    }
            //    this.ShowMsg("pass");
            //}
        }
    }
}
